import {useState, useEffect} from 'react';
import logo from './assets/images/logo-universal.png';
import './App.css';
import {SelectDirectory, CheckMkDocsInitialized, InitializeMkDocs, StartMkDocsServe, CheckEnvironment, InstallMkDocs, GetEnvironmentDetails} from "../wailsjs/go/main/App";
import {EventsOn} from "../wailsjs/runtime/runtime";

function App() {
    const [directory, setDirectory] = useState('');
    const [port, setPort] = useState('8111');
    const [status, setStatus] = useState('请选择MkDocs项目目录');
    const [isInitialized, setIsInitialized] = useState(false);
    const [isLoading, setIsLoading] = useState(false);
    const [mkdocsUrl, setMkdocsUrl] = useState('');
    const [isServerRunning, setIsServerRunning] = useState(false);
    const [environment, setEnvironment] = useState(null);
    const [envDetails, setEnvDetails] = useState(null);
    const [showEnvDetails, setShowEnvDetails] = useState(false);
    const [isInstalling, setIsInstalling] = useState(false);

    // Check environment on startup
    useEffect(() => {
        const checkEnvironment = async () => {
            try {
                const envCheck = await CheckEnvironment();
                setEnvironment(envCheck);
                
                if (!envCheck.PythonAvailable) {
                    setStatus(envCheck.ErrorDetails || '需要安装Python 3.6+');
                } else if (!envCheck.PipAvailable) {
                    setStatus(envCheck.ErrorDetails || '需要安装pip');
                } else if (!envCheck.MkDocsAvailable) {
                    setStatus('MkDocs未安装');
                } else {
                    setStatus('环境就绪');
                }
                
                // Get environment details for display
                const details = await GetEnvironmentDetails();
                setEnvDetails(details);
            } catch (error) {
                setStatus('环境检查失败: ' + error);
            }
        };
        
        checkEnvironment();
    }, []);

    // Set up event listener for MkDocs server start
    useEffect(() => {
        EventsOn('mkdocs-started', (url) => {
            setMkdocsUrl(url);
            setIsServerRunning(true);
            setStatus('MkDocs服务已启动');
        });
    }, []);

    const handleSelectDirectory = async () => {
        try {
            const selectedDir = await SelectDirectory();
            if (selectedDir) {
                setDirectory(selectedDir);
                setIsLoading(true);
                const initialized = await CheckMkDocsInitialized(selectedDir);
                setIsInitialized(initialized);
                setStatus(initialized ? 'MkDocs项目已初始化' : 'MkDocs项目未初始化');
                setIsLoading(false);
            }
        } catch (error) {
            setStatus('选择目录失败: ' + error);
            setIsLoading(false);
        }
    };

    const handleInitialize = async () => {
        if (!directory) return;
        setIsLoading(true);
        try {
            const result = await InitializeMkDocs(directory);
            setStatus(result);
            if (result.includes('成功')) {
                setIsInitialized(true);
            }
        } catch (error) {
            setStatus('初始化失败: ' + error);
        } finally {
            setIsLoading(false);
        }
    };

    const handleStartServe = async () => {
        if (!directory || !port) return;
        setIsLoading(true);
        try {
            const result = await StartMkDocsServe(directory, port);
            setStatus(result);
        } catch (error) {
            setStatus('启动服务失败: ' + error);
        } finally {
            setIsLoading(false);
        }
    };

    const handleStopServer = () => {
        setMkdocsUrl('');
        setIsServerRunning(false);
        setStatus('MkDocs服务已停止');
    };

    const handleInstallMkDocs = async () => {
        if (isInstalling || !environment) return;
        
        setIsInstalling(true);
        setStatus('正在安装MkDocs...');
        
        try {
            const result = await InstallMkDocs(environment);
            setStatus(result);
            if (result.includes('成功')) {
                // 重新检查环境
                const envCheck = await CheckEnvironment();
                setEnvironment(envCheck);
                
                // 更新环境详情
                const details = await GetEnvironmentDetails();
                setEnvDetails(details);
                
                setStatus('环境就绪');
            }
        } catch (error) {
            setStatus('安装MkDocs失败: ' + error);
        } finally {
            setIsInstalling(false);
        }
    };

    const handleToggleEnvDetails = async () => {
        if (showEnvDetails) {
            setShowEnvDetails(false);
        } else {
            // 重新获取最新环境详情
            try {
                const details = await GetEnvironmentDetails();
                setEnvDetails(details);
                setShowEnvDetails(true);
            } catch (error) {
                setStatus('获取环境详情失败: ' + error);
            }
        }
    };

    return (
        <div id="App">
            <div className="control-panel">
                <div className="control-row">
                    <div className="directory-input">
                        <button className="btn" onClick={handleSelectDirectory} disabled={isLoading}>
                            选择目录
                        </button>
                        <input 
                            type="text" 
                            value={directory} 
                            placeholder="选择的目录路径" 
                            readOnly
                            className="input"
                        />
                    </div>
                    
                    <div className="port-control">
                        <label>端口:</label>
                        <input 
                            type="number" 
                            value={port} 
                            onChange={(e) => setPort(e.target.value)}
                            placeholder="8000"
                            className="input"
                            min="1"
                            max="65535"
                            disabled={isServerRunning}
                        />
                    </div>

                    <div className="action-buttons">
                        {environment && !environment.MkDocsAvailable && environment.PythonAvailable && environment.PipAvailable && (
                            <button 
                                className="btn btn-warning"
                                onClick={handleInstallMkDocs}
                                disabled={isInstalling}
                            >
                                {isInstalling ? '安装中...' : '安装MkDocs'}
                            </button>
                        )}
                        
                        {environment && environment.MkDocsAvailable && !isServerRunning && (
                            <button 
                                className={`btn ${isInitialized ? 'btn-primary' : 'btn-success'}`}
                                onClick={isInitialized ? handleStartServe : handleInitialize}
                                disabled={!directory || isLoading}
                            >
                                {isLoading ? (isInitialized ? '启动中...' : '初始化中...') : (isInitialized ? '启动服务' : '初始化项目')}
                            </button>
                        )}
                        
                        <button 
                            className="btn btn-info"
                            onClick={handleToggleEnvDetails}
                        >
                            {showEnvDetails ? '隐藏详情' : '环境检查'}
                        </button>
                        
                        {isServerRunning && (
                            <button 
                                className="btn btn-danger" 
                                onClick={handleStopServer}
                            >
                                停止服务
                            </button>
                        )}
                    </div>

                    <div className="status-tag">
                        <span className={`status-indicator ${isServerRunning ? 'running' : isInitialized ? 'ready' : (environment && environment.MkDocsAvailable && environment.PythonAvailable && environment.PipAvailable) ? 'idle' : 'error'}`}>
                            {isServerRunning ? '运行中' : isInitialized ? '就绪' : (environment && environment.MkDocsAvailable && environment.PythonAvailable && environment.PipAvailable) ? '未就绪' : '需要安装'}
                        </span>
                    </div>
                </div>
            </div>

            {showEnvDetails && envDetails && (
                <div className="env-details-panel">
                    <div className="env-details-header">
                        <h3>环境检查结果</h3>
                        <button className="btn btn-close" onClick={() => setShowEnvDetails(false)}>
                            ✕
                        </button>
                    </div>
                    <div className="env-details-content">
                        <div className="env-status-list">
                            <div className={`env-status-item ${envDetails.pythonAvailable ? 'success' : 'error'}`}>
                                <span className="env-status-icon">{envDetails.pythonAvailable ? '✓' : '✗'}</span>
                                <span className="env-status-text">Python {envDetails.pythonAvailable ? '已安装' : '未安装'}</span>
                            </div>
                            <div className={`env-status-item ${envDetails.pipAvailable ? 'success' : 'error'}`}>
                                <span className="env-status-icon">{envDetails.pipAvailable ? '✓' : '✗'}</span>
                                <span className="env-status-text">pip {envDetails.pipAvailable ? '已安装' : '未安装'}</span>
                            </div>
                            <div className={`env-status-item ${envDetails.mkdocsAvailable ? 'success' : 'error'}`}>
                                <span className="env-status-icon">{envDetails.mkdocsAvailable ? '✓' : '✗'}</span>
                                <span className="env-status-text">MkDocs {envDetails.mkdocsAvailable ? '已安装' : '未安装'}</span>
                            </div>
                        </div>
                        {envDetails.pythonPath && (
                            <div className="env-detail-item">
                                <strong>Python路径:</strong> {envDetails.pythonPath}
                            </div>
                        )}
                        {envDetails.pipCommand && (
                            <div className="env-detail-item">
                                <strong>pip命令:</strong> {envDetails.pipCommand}
                            </div>
                        )}
                        <div className="env-guidance">
                            <strong>处置指引:</strong>
                            <pre className="guidance-text">{envDetails.guidance}</pre>
                        </div>
                    </div>
                </div>
            )}

            {isServerRunning && mkdocsUrl && (
                <div className="browser-container">
                    <div className="browser-frame">
                        <iframe 
                            src={mkdocsUrl}
                            title="MkDocs Preview"
                            className="browser-iframe"
                            sandbox="allow-same-origin allow-scripts allow-forms"
                        />
                    </div>
                </div>
            )}
        </div>
    )
}

export default App
